package com.hzy.kafka.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.ConcurrentKafkaListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.listener.MessageListenerContainer;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class KafkaConsumerService {

    @KafkaListener(groupId = "group02", topics = "topic02")
    public void onMessage(ConsumerRecord<String, Object> record, Acknowledgment acknowledgment, Consumer<?, ?> consumer) {
        log.info("消费端接收消息: {}", record.value());
        //	手工签收
        acknowledgment.acknowledge();
    }

    @KafkaListener(topics = "myJob")
    @SendTo("myJob-delay")
    public String onMessage(ConsumerRecord<?, ?> cr, Acknowledgment ack) {
        // 传入参数
        String json = (String) cr.value();
        JSONObject data = JSON.parseObject(json);
        long msToDelay = data.getLong("msToDelay");
        if (msToDelay > 0) {
            // 提交
            ack.acknowledge();
            // 发送到 @SendTo
            data.put("until", System.currentTimeMillis() + msToDelay);
            return data.toString();
        }

        // 正常处理
        // do real work

        // 提交
        ack.acknowledge();
        return null;
    }

    @KafkaListener(topics = "myJob-delay")
    @SendTo("myJob")
    public String delayMessage(ConsumerRecord<?, ?> cr, Acknowledgment ack) throws InterruptedException {
        // 传入参数
        String json = (String) cr.value();
        JSONObject data = JSON.parseObject(json);
        Long until = data.getLong("until");
        // 阻塞直到 until
        while (System.currentTimeMillis() < until) {
            Thread.sleep(Math.max(0, until - System.currentTimeMillis()));
        }
        // 提交
        ack.acknowledge();
        // 转移到 @SendTo
        return json;
    }

    @Autowired
    private KafkaListenerEndpointRegistry registry;

    /**
     * 定时执行
     *
     * @param recordList
     * @param acknowledgment
     */
    @KafkaListener(id = "test-task", topics = {"test-task"}, groupId = "test-topic", containerFactory = "batchFactory")
    public void listenFailEmail(List<ConsumerRecord> recordList, Acknowledgment acknowledgment) {
        for (ConsumerRecord record : recordList) {
            log.info("fail email-消息：【{}】。", record.toString());
        }
        acknowledgment.acknowledge();
    }

    @Scheduled(cron = "0 53 20 * * ?")
    public void startListener() {
        log.info("开启监听");
        MessageListenerContainer container = registry.getListenerContainer("test-task");
        if (!container.isRunning()) {
            container.start();
        }
        //恢复
        container.resume();
    }

    @Scheduled(cron = "0 54 20 * * ?")
    public void shutdownListener() {
        log.info("关闭监听");
        //暂停
        MessageListenerContainer container = registry.getListenerContainer("test-task");
        container.pause();
    }
}


